package com.jhz.speedy.component.net;

import android.text.TextUtils;

import com.jhz.speedy.R;
import com.jhz.speedy.common.util.LogUtils;
import com.jhz.speedy.common.util.ToastUtils;
import com.jhz.speedy.component.application.MyApplication;
import com.jhz.speedy.logic.apiservice.APIConstance;
import com.jhz.speedy.logic.entity.response.BaseResponse;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络工具
 * Created by JunHeZ on 2017/6/29.
 */
public class NetManager {
    private final String TAG = getClass().getSimpleName();
    private static NetManager netManager;
    private Retrofit retrofit;  // 自己服务器
    private Retrofit retrofitBaidu; // 百度

    private NetManager(){
        init();
    }

    public static NetManager getInstance(){
        if(netManager == null)
            netManager = new NetManager();

        return netManager;
    }

    /**
     * 初始化
     */
    private void init() {
        // HTTP缓存在 CacheDir/HttpCache
        File cacheFile = new File(MyApplication.getInstance().getCacheDir(), "HttpCache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(new MyLogInterceptor())
                .cache(cache)
                .build();

        // baseUrl必须以/结尾
        retrofit = new Retrofit.Builder()
                .baseUrl(APIConstance.SERVER_IP_BUSINESS_SHORT)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        retrofitBaidu = new Retrofit.Builder()
                .baseUrl(APIConstance.SERVER_BAIDU)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
    }

    /**
     * 获取API服务类
     */
    public <T> T getAPIService(final Class<T> service) {
        return retrofit.create(service);
    }

    /**
     * 获取百度API服务类
     */
    public <T> T getBaiduAPIService(final Class<T> service) {
        return retrofitBaidu.create(service);
    }

    public void callService(Call<BaseResponse> call, final String apiName, final ActionCallBack callBack){
        callService(call, apiName, true, callBack);
    }

    /**
     * 请求
     * @param call  请求
     * @param tag   标签
     * @param isAutoToast   是否自动Toast
     * @param callBack  回调
     */
    public void callService(Call<BaseResponse> call, final String tag, final boolean isAutoToast, final ActionCallBack callBack){
        // 回调结果
        final ActionResult finalResult = new ActionResult();
        finalResult.tag = tag;

        // 加入请求队列，开始请求
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                BaseResponse baseResponse = null;  // 我们服务响应实体
                try {
                    baseResponse = response.body();
                    if(baseResponse != null){
                        if(baseResponse.getStatus() == BaseResponse.STATUS_OK){
                            finalResult.state = ActionResult.STATE_OK;  // 成功

                        }else {
                            // 服务器如有错误提示，则使用服务器的提示
                            LogUtils.e(TAG, "tag = " + tag + " baseResponse = null");

                            if(isAutoToast){
                                if(TextUtils.isEmpty(baseResponse.getMsg())){
                                    ToastUtils.toast(R.string.data_exception_);
                                }else {
                                    ToastUtils.toast(baseResponse.getMsg());
                                }
                            }
                        }
                    }else {
                        if(isAutoToast){
                            ToastUtils.toast(R.string.data_exception);
                        }
                        LogUtils.e(TAG, "tag = " + tag + " baseResponse = null");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    if(isAutoToast){
                        ToastUtils.toast(R.string.data_exception);
                    }
                    finalResult.state = ActionResult.STATE_ERROR_RESPOND;   // 数据异常
                }
                finalResult.data = baseResponse;    // 响应实体
                callBack.onResult(finalResult);
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                // 网络异常
                t.printStackTrace();
                if(isAutoToast){
                    ToastUtils.toast(R.string.network_exception_please_try_again_later);
                }
                finalResult.state = ActionResult.STATE_ERROR_CODE;
                callBack.onResult(finalResult);
            }
        });
    }
}
